#支付宝蚂蚁森林主策略
import time
import Comment
import sys
import random
import os
class Alipay:
    def __init__(self,queue,final=0):
        self.remote = 1
        self.final = final
        self.swipePath = r'G:\python-control-phone\alipay\2'
        self.swipeFile = 'swipe'
        self.className = 'Alipay'
        #未识别场景存放路径
        self.unknownpath = r'G:\python-control-phone\alipay\unknown'
        #截图存放地址
        self.shotpath = 'G:\python-control-phone\img'
        self.shotpFullPath = R'G:\python-control-phone\img\tmp.jpg'
        #日志名
        self.log = r'tldk';
        #未命中响应场景 休眠时间
        self.sleepTime = 5
        #超出试错次数终止程序 
        self.times = 2
        self.queue = queue
        #固定场景字典
        self.stage = {
            #手机解锁主屏
            'home':{
                    #场景
                    'stage':r'G:\python-control-phone\alipay\1\home.png',
                    #响应场景
                    'activeStage':{
                                    #动作1
                                    'openAlipay':{
                                                #未命中：执行方法
                                                'miss':'home',
                                                #命中:匹配图
                                                'hit':r'G:\python-control-phone\alipay\1\open.png',
                                                },
                                    },
                    },
            #锁屏场景
            'lock':{
                    #场景
                    'stage':r'G:\python-control-phone\alipay\1\lock.png',
                    #响应场景
                    'activeStage':{
                                    #动作1
                                    'myLock':{
                                                #未命中：执行方法
                                                'miss':'next',
                                                #命中:匹配图
                                                'hit':r'G:\python-control-phone\alipay\1\lock.png',
                                                },
                                    },
                    },
            #支付宝里
            'anttree':{
                    #场景
                    'stage':r'G:\python-control-phone\alipay\2\anttree.png',
                    #响应场景
                    'activeStage':{
                            #动作1
                                    'openAntTree':{
                                                #未命中：执行方法
                                                'miss':'home',
                                                #命中:匹配图
                                                'hit':r'G:\python-control-phone\alipay\2\anttree.png',
                                                },
                                  },
                    },
            #蚂蚁森林游戏中
            'game':{
                #场景
                'stage':r'G:\python-control-phone\alipay\2\tree.png',
                #响应场景
                'activeStage':{
                                #动作1 查询更多好友
                                'getSelf':{
                                             'miss':'next',
                                             'hit':r'G:\python-control-phone\alipay\2\self.png'
                                            },
                                 'clickFriend':{
                                     'miss':'swipe',
                                     'hit':r'G:\python-control-phone\alipay\2\more.png'
                                  },
                            },
                },
             #查找更多朋友
             'more':{
             #场景
                'stage':r'G:\python-control-phone\alipay\2\more.png',
                 #响应场景
                'activeStage':{
                    'clickFriend':{
                                     'miss':'swipe',
                                     'hit':r'G:\python-control-phone\alipay\2\more.png'
                                  },
                               },
                },
             #查找朋友
            'friend':{
                'stage':r'G:\python-control-phone\alipay\2\friend.png',
                'activeStage':{
                                'getHand':{
                                             'miss':'swipe',
                                             'hit':r'G:\python-control-phone\alipay\2\hand.png'
                                           },
                                'getFriend':{
                                             'miss':'back',
                                             'hit':r'G:\python-control-phone\alipay\2\get.png'
                                      },
                               },
                    },
            #朋友收集能量球中
            'friend_in': {
                'stage': r'G:\python-control-phone\alipay\2\sms.png',
                'activeStage': {
                    'getFriend': {
                        'miss': 'back',
                        'hit': r'G:\python-control-phone\alipay\2\get.png'
                    },
                },
            }
        }
    #自定义解锁L形
    def myLock(self,res):
        os.system(
            'adb shell sendevent /dev/input/event2 0003 0057 00008780 &adb shell sendevent /dev/input/event2 0001 0330 00000001 &adb shell sendevent /dev/input/event2 0003 0053 00000567 &adb shell sendevent /dev/input/event2 0003 0054 00000739 &adb shell sendevent /dev/input/event2 0003 0049 00000004 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000553 &adb shell sendevent /dev/input/event2 0003 0054 00000798 &adb shell sendevent /dev/input/event2 0003 0048 00000006 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000502 &adb shell sendevent /dev/input/event2 0003 0054 00001360 &adb shell sendevent /dev/input/event2 0003 0049 00000004 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000530 &adb shell sendevent /dev/input/event2 0003 0054 00001395 &adb shell sendevent /dev/input/event2 0003 0048 00000005 &adb shell sendevent /dev/input/event2 0003 0049 00000003 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0053 00000926 &adb shell sendevent /dev/input/event2 0003 0054 00001404 &adb shell sendevent /dev/input/event2 0003 0048 00000005 &adb shell sendevent /dev/input/event2 0000 0000 00000000 &adb shell sendevent /dev/input/event2 0003 0057 4294967295 &adb shell sendevent /dev/input/event2 0000 0000 00000000')
        self.showMsg('执行解锁')
        self.actionSleep(5)
    def setFinal(self,value):
        self.final = value
    #未命中执行上下滑动搜寻场景目标
    def swipe(self):
        #关闭任务
        closePic =r'G:\python-control-phone\alipay\2\close.png'
         #写入队列场景
        self.showMsg('主线程：匹配是否存在任务')
        self.showStage(closePic)
        res = Comment.matchImg("%s\\tmp.jpg"%(self.shotpath),closePic,0.9)
        self.showMsg(res)
        if(res):
            self.showMsg('主线程：发现任务,关闭任务')
            self.click(res)
        else:
            self.showMsg('主线程：不存在任务弹框,判断是否滑动到底')
            time.sleep(1)
            Comment.screenShot(self.shotpath)
            print(os.path.exists("%s\\%s.jpg"%(self.swipePath,self.swipeFile)))
            if os.path.exists("%s\\%s.jpg"%(self.swipePath,self.swipeFile)):
                res =Comment.matchImg("%s\\tmp.jpg"%(self.shotpath),"%s\\%s.jpg"%(self.swipePath,self.swipeFile),0.9)
                if res:
                    self.showMsg(res)
                    self.showMsg('发现已滚动到底部')
                    self.showMsg('final为%s'%(self.final))
                   #判断方向
                    if self.final == 1:
                        #下滑动
                        self.swipe_down()
                        self.final = 0
                        self.showMsg('final置为%s'%(self.final))
                    else:
                        self.swipe_up()
                        self.final = 1
                        self.showMsg('!!!!!!!!!final置为%s'%(self.final))
                else:
                    self.showMsg('final为%s'%(self.final))
                    if self.final == 1:
                        self.swipe_up()
                    else:
                        self.swipe_down()
            Comment.screenShot(self.swipePath,self.swipeFile)
            self.showStage("%s\\%s.jpg" % (self.swipePath, self.swipeFile))
            self.showMsg('留存本次滑动截图,休眠5s')
            time.sleep(1)
            return self.final
    def swipe_down(self):
        self.showMsg('执行向下滑动操作')
        Comment.swipe_screen(718,1000,818,418,150)
    def swipe_up(self):
        self.showMsg('执行向上滑动操作')
        Comment.swipe_screen(818,418,718,1000,150)
    #响应场景事件
    #打开支付宝
    def openAlipay(self,res):
        x,y = res['result']
        k = (x,y-90)
        self.click(k)
        self.showMsg('正在打开支付宝APP')
        self.actionSleep(10)
    #打开蚂蚁森林
    def openAntTree(self,res):
        self.click(res)
        self.showMsg('正在打开蚂蚁森林')
        self.actionSleep(10)
    #收取自己
    def getSelf(self,res):
        self.click(res)
        self.showMsg('正在收取自己能量球')
        self.actionSleep(2)
    #查看更多好友
    def clickFriend(self,res):
        self.click(res)
        self.showMsg('查看更多好友')
        self.actionSleep(5)
    def getFriend(self,res):
        #增加坐标偏移
        x,y = res['result']
        k = (x,y-90)
        self.click(k)
        self.showMsg('正在收取朋友能量球')
        self.actionSleep(2)
    def getHand(self,res):
        self.click(res)
        self.showMsg('查找朋友谁有能量球')
        self.actionSleep(5)
     
    #倒计时休眠
    def actionSleep(self,t):
        while t:
              self.showMsg("倒计时 %s 秒"%(t))
              time.sleep(1)
              t=t-1
    #点击事件
    def click(self,res):
        if 'result' in res:
            x,y = res['result']
        else:
            x,y = res
        Comment.tap_screen(x,y)
        #画图保存
        self.drawCircle(res)
    #画圆圈
    def drawCircle(self,res):
        Comment.click_draw(self.shotpFullPath,res)
        self.showAction(self.shotpFullPath)
    def sleep(self):
        self.showMsg('未命中响应场景，休眠10s...')
        time.sleep(10)
        Comment.tap_screen(700,1400)
    #打开游戏
    def gameStart(self,result):
        x,y = result['result']
        Comment.tap_screen(x,y)
        #画图保存
        Comment.click_draw(self.shotpFullPath,result)
        self.showAction(self.shotpFullPath)
        self.showMsg('点击坐标%s%s'%(x,y))
        self.showMsg('正在打开游戏.....休眠15s')
        time.sleep(15)
    def write_log(self,message):
        Comment.log(message,self.log)
    #滑屏寻找app
    def home(self):
        Comment.swipe_screen(718,1367,335,1367,800)
        Comment.screenShot(self.shotpath)
    #打开目标
    def openApp(self,result):
        x,y = result['result']
        Comment.tap_screen(x,y)
        #画图保存
        #print(result)
        Comment.click_draw(self.shotpFullPath,result)
        self.showAction(self.shotpFullPath)
        self.showMsg('点击坐标%s%s'%(x,y))
        self.showMsg('点击坐标%s%s'%(x,y))
        self.showMsg('正在打开目标.....休眠10s')
        time.sleep(10)
    #显示消息
    def showMsg(self,msg):
        print("%s | 行号:%s"%(msg,sys._getframe().f_back.f_lineno))
        content = Comment.formatMsg(msg)
        Comment.putQueue(self.queue ,content)
    #显示图片
    def showStage(self,path):
        print(path)
        content = Comment.formatStage(path)
        Comment.putQueue(self.queue ,content)
    def showAction(self,path):
        print(path)
        content = Comment.formatAction(path)
        Comment.putQueue(self.queue ,content)
    def back(self):
        Comment.back()
        self.showMsg('返回上一页.....休眠3s')
        time.sleep(3)
    def clickHome(self,res):
        Comment.home()
        self.showMsg('返回HOME.....休眠1s')
        time.sleep(1)
    #主策略
    def Start(self,unknown = 0):
        #实例化函数
        mod = eval(self.className)(self.queue,self.final)
        self.showMsg(mod)
        #滑动到底部 1为到 0为未到
        stageKey = 0
        #手机截图并存放到指定目录返回目录
        result = Comment.screenShot(self.shotpath)
        if result:
            self.showMsg('截图成功')
            self.showAction(result)
            #取出场景
            for key in self.stage:
                #写入队列场景
                self.showStage(self.stage[key]['stage'])
                #exit()
                res = Comment.matchImg(result,self.stage[key]['stage'],0.9)
                self.showMsg(res)
                #exit()
                self.showMsg('<<<<<<<搜寻所处场景>>>>>>>')
                #获取匹配场景
                if res:
                    stageKey = key
                    self.showMsg("####已匹配到#### 处在场景%s"%(key))
                    time.sleep(3)
                    unknown = 1
                    #exit()
                    break;
            if stageKey == 0:
                Comment.screenShot(self.unknownpath)
                if unknown > 0:
                    self.showMsg('!!!!!!未知场景')
                    self.write_log("!!!!!未知场景: %s"%(key))
                    self.showMsg('退出')
                    exit()
                self.showMsg('~~~~~初始化到首页~~~~~')
                Comment.home()
                return self.Start()
        else:
            self.showMsg('未获取到手机截图')
            exit()
        #调用响应场景
        self.showMsg('<<<<<<<<搜寻响应场景>>>>>>>>')
        for k in self.stage[stageKey]['activeStage']:
            #展示场景
            self.showStage(self.stage[stageKey]['activeStage'][k]['hit'])
            while True:
                print("!!!!!!!!!final当前为%s"%(self.final))
                if unknown > 15:
                    self.back()
                    break;
                if unknown >100:
                    Comment.screenShot(self.unknownpath)
                    self.showMsg('!!!!!!未知响应场景')
                    self.write_log("!!!!!未知响应场景: %s"%(key))
                    self.showMsg('退出')
                    exit()                   
                #self.showMsg(self.stage[stageKey]['activeStage'][k])
                #exit()
                result = Comment.screenShot(self.shotpath)
                self.showAction(result)
                print('\n\n\n开始计算匹配度>>>>>>>>>>')
                #点击水晶球多个目标 点自己的
                if(k=='getSelf' and stageKey=='game'):
                    res = Comment.matchImgs(result,self.stage[stageKey]['activeStage'][k]['hit'])
                    print(res)
                    #exit()
                    if res:
                        #找到函数方法
                        self.showMsg("@@@@找到自己的能量球%s"%(k))
                        fun = getattr(mod,k)
                        for xk in res:
                            fun(xk)
                            time.sleep(1)
                            self.showMsg("@@@点击目标")
                    else:
                        self.showMsg("@@@@未找到自己的能量球%s"%(k))
                    break
                #点击水晶球多个目标 点朋友的
                if(k=='getFriend' and stageKey=='friend'):
                    #匹配之前灰度处理
                    res = Comment.matchImgs(result,self.stage[stageKey]['activeStage'][k]['hit'],0.8)
                    print(res)
                    #exit()
                    self.showMsg("@@@@找到朋友能量球%s"%(k))
                    fun = getattr(mod,k)
                    for fk in res:
                        fun(fk)
                        time.sleep(2)
                        self.showMsg("@@@点击目标%s"%(fk['result'],))
                    
                    time.sleep(5)
                    #点完毕返回朋友列表
                    fun = getattr(mod,self.stage[stageKey]['activeStage'][k]['miss'])
                    #back 1次可以跳过能量保护罩
                    fun()
                    #fun()
                    break
                else:
                    res = Comment.matchImg(result,self.stage[stageKey]['activeStage'][k]['hit'],0.8)
                print(res)
                #主响应策略
                if res:
                    self.showMsg("@@@@找到响应场景%s"%(k))
                    #找到函数方法
                    fun = getattr(mod,k)
                    fun(res)
                    break
                else:
                    self.showMsg("@@@@未命中响应场景%s"%(k))
                    #判断miss场景
                    self.showMsg("执行miss方法%s"%(self.stage[stageKey]['activeStage'][k]['miss']))
                    #time.sleep(5)
                    fun = getattr(mod,self.stage[stageKey]['activeStage'][k]['miss'])
                    #找不到能量球朋友场景 上下滑动
                    if(self.stage[stageKey]['activeStage'][k]['miss'] =='swipe'):
                        print("!!!!!!!!!final当前为%s"%(self.final))
                        self.final = fun()
                    elif(self.stage[stageKey]['activeStage'][k]['miss'] =='next'):
                        self.showMsg("@@@@未找到响应场景%s,跳出寻找场景" % (k))
                        break
                    else:
                        print("miss函数当前为%s"%(self.stage[stageKey]['activeStage'][k]['miss']))
                        fun()
                    unknown = unknown+1
                    self.showMsg("***********未命中置为%s"%(unknown))
        return self.Start(unknown)
                
    